package com.wltt.healing.healingusercommon.utils;

import org.springframework.cglib.beans.BeanCopier;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: wltt
 * @Date: 2021/9/8 15:26：
 * @Version: 1.0
 * @Description: TODO
 */
public abstract class BeanCopierUtil {

    private static Map<String, BeanCopier> BEAN_COPIER_MAP = new ConcurrentHashMap();

    /**
     * 对象复制
     *
     * @param source 源
     * @param target 目标
     */
    public static void copyProperties(Object source, Object target) {
        if (source == null) {
            throw new RuntimeException("源对象不能为空");
        }
        if (target == null) {
            throw new RuntimeException("目标对象不能为空");
        }

        // 获取key
        StringBuilder sb = new StringBuilder(source.getClass().getName());
        sb.append(target.getClass().getName());
        String key = sb.toString();

        // 获取copier
        BeanCopier copier = BEAN_COPIER_MAP.get(key);
        if (copier == null) {
            copier = BeanCopier.create(source.getClass(), target.getClass(), false);
            BEAN_COPIER_MAP.put(key, copier);
        }

        // 复制
        copier.copy(source, target, null);
    }
}
